# -*- coding: utf-8 -*-
import re
import os
import tempfile



# 货币字典
CurrencyDictionary={
    '000':"CNY",
    '001':"CNY",
    '011':'CNY',
    '002':'AUA',
    '003':'AUB',
    '010':'BDT',
    '012':'GBP',
    '013':'HKD',
    '014':'USD',
    '015':'CHF',
    '016':'DEM',
    '017':'FRF',
    '018':'SGD',
    '019':'PKR',
    '020':'NLG',
    '021':'SEK',
    '022':'DKK',
    '023':'NOK',
    '027':'JPY',
    '028':'CAD',
    '029':'AUD',
    '030':'TZS',
    '031':'ESP',
    '032':'MYR',
    '033':'XEU',
    '034':'XAU',
    '035':'GLD',
    '036':'XAG',
    '037':'XDR',
    '038':'EUR',
    '040':'LKR',
    '041':'DZD',
    '042':'FIM',
    '044':'IQD',
    '046':'MAD',
    '047':'SLL',
    '048':'IRR',
    '049':'NPR',
    '060':'CNY',
    '061':'ALL',
    '063':'KPW',
    '064':'VND',
    '066':'BGL',
    '070':'ZAR',
    '071':'LYD',
    '080':'ZMK',
    '081':'MOP',
    '082':'PHP',
    '084':'THB',
    '085':'INR',
    '087':'NZD',
    '088':'KRM',
    '089':'SYP',
    '094':'USD',
    '095':'CHF',
    '240':'ROL',
    '601':'GHC'
}


src = r'C:\Users\sherry\Desktop\ODMS测试数据\内蒙古\RNM000.00000060.测试数据\RNM000.00000060.DTP.202510100'
dst = r'C:\Users\sherry\Desktop\NEW_OUT.txt'

import mmap

def pipe_to_enhanced_pipe(src_file: str) -> None:
    """
    把 src_file 里除最后一行外的所有 '|' 替换成 '|'，最后一行保持原样。
    原地修改，不生成新文件。
    """
    if not os.path.isfile(src_file):
        raise FileNotFoundError(src_file)
    new_lines = []
    with open(src_file, "r", encoding="utf-8") as f:
        src_lines = f.readlines()
        length = len(src_lines)
        # print(type(src_lines[0]))
        for i in range(length-1):
            new_lines.append(src_lines[i].replace("|", "|"))
        new_lines.append(src_lines[length-1])
        # for line in new_lines:
        #     print(line)
    with open(src, "w", encoding="utf-8") as f:
        f.writelines(new_lines)


# def add_seq_and_pipe_inplace(path: str) -> None:
#     """
#     原地给每条记录加序号| 并在行尾补 |
#     失败不会破坏原文件
#     """
#     # 临时文件放在同目录，确保原子替换跨盘也能成功
#     tmp = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8',
#                                       delete=False, dir=os.path.dirname(path))
#     try:
#         with open(path, 'r', encoding='utf-8') as fin, tmp:
#             for idx, line in enumerate(fin, 1):
#                 line = line.rstrip('\n')
#                 tmp.write(f'{idx}|{line}|\n')
#
#         tmp.close()
#         # 原子替换：要么成功，要么抛异常，原文件始终完好
#         os.replace(tmp.name, path)
#     except Exception:
#         # 异常时把临时文件清掉，再向上抛
#         os.unlink(tmp.name)
#         raise
#
#
# def flatten_dates(row: str) -> str:
#     """
#     把行内所有 |YYYY-MM-DD| 形式的日期改成 |YYYYMMDD|
#     """
#
#     def _fmt(m):
#         return m.group(0).replace('-', '')
#
#     # 正则要的是“被 | 包围的日期”，所以用 look-behind & look-ahead
#     return re.sub(r'(?<=\|)\d{4}-\d{2}-\d{2}(?=\|)', _fmt, row)
#
#
# def replace_pipe_field(row: str, n: int, new_val: str) -> str:
#     """
#     把 row 中第 n 个 | 到第 n+1 个 | 之间的内容替换成 new_val
#     n 从 1 开始计数
#     """
#     # 为了兼容末尾的 |^ENDROW，先在最右边保证有一个 |
#
#
#     # 找到所有 | 的下标
#     idx = [i for i, ch in enumerate(row) if ch == '|']
#
#     # 边界检查
#     if n < 1 or n + 1 >= len(idx):
#         raise IndexError('n 超出已有 | 的范围')
#
#     # 切片替换
#     start = idx[n - 1] + 1          # 第 n 个 | 的下一个字符
#     end   = idx[n]                  # 第 n+1 个 |
#     return row[:start] + new_val + row[end:]
#
# with open(src, 'r', encoding='utf-8') as f:
#     records = f.readlines()
#
#     i = 1
#     new_records = []
#     for record in records:
#         if(i <= 10):
#             new_records.append(flatten_dates(replace_pipe_field(record, 4, '1010')))
#         elif i> 10 and i <= 20:
#             new_records.append(flatten_dates(replace_pipe_field(record, 4, '1322')))
#         elif i> 20 and i <= 30:
#             new_records.append(flatten_dates(replace_pipe_field(record, 4, '2010')))
#         elif i> 30 and i <= 1000:
#             new_records.append(flatten_dates(replace_pipe_field(record, 4, '2310')))
#         i = i +1
#
# with open(dst, 'w', encoding='utf-8') as f:
#     f.writelines(new_records)

src = r'C:\Users\sherry\Desktop\ODMS测试数据\内蒙古\RNM000.00000060.测试数据\RNM000.00000060.DTP.202510100'

def modify_data(src):

    new_lines = []
    with open(src, "r", encoding="utf-8") as f:
        src_lines = f.readlines()
        for line in src_lines:
            # marker = '|'  # 竖线 + 0x01
            # print(line)
            # print(line.find(marker)+len(marker))
            # print(line[line.find(marker)+len(marker)])

            # print(line)
            # line = line.split(marker, 1)[-1] if marker in line else line
            new_lines.append(line[10:])
            # print(new_lines)
    with open(src, "w", encoding="utf-8") as f:
        f.writelines(new_lines)
    return


def main():
    modify_data(src)
    return


if __name__ == '__main__':
    main()
